import {Injectable} from '@angular/core';
import {
  CanActivate, Router,
  CanActivateChild,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
}                           from '@angular/router';
import {user} from '../user/user.service';
import {MyHttp} from '../myHttp/myhttp.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/map';
//import 'rxjs/add/operator/toPromise';
@Injectable()
export class LoginGuard implements CanActivate,CanActivateChild{
  constructor(private myHttp:MyHttp,private router:Router){

  }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean|Promise<boolean>{
    let isSignIn=!!user.isSignIn;
    console.log(isSignIn);
    if(isSignIn) {
      return true;
    }else{
      return this.myHttp.post({
        api: this.myHttp.api.auth,
        body:{token:user.getToken()}
      }).toPromise()
        .then((res)=>{
          let isSuccess=res.status===200?res.json().status:false;
          if(isSuccess) {
            console.log(user.redirectTo);
            let newUser=res.json().data;
            user.setUserId(newUser.userId);
            user.setAuth(newUser.auth);
            user.setToken(newUser.token);
            user.setUserName(newUser.username);
            user.setUserType(newUser.userType);
            user.setSignIn(true);
            if(user.redirectTo){
              this.router.navigate([user.redirectTo]);
            }
          }
          return Promise.resolve(isSuccess);
        });
    }
  }
  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean|Promise<boolean> {


    let isSignIn=!!user.isSignIn;
    console.log(isSignIn);
    if(isSignIn) {
      return true;
    }else{
      return this.myHttp.post({
        api: this.myHttp.api.auth,
        body:{token:user.getToken()}
      }).toPromise()
        .then(function(res){
          let isSuccess=res.status===200?res.json().status:false;
          if(isSuccess) {
            let newUser=res.json().data;
            user.setUserId(newUser.userId);
            user.setAuth(newUser.auth);
            user.setToken(newUser.token);
            user.setUserName(newUser.username);
            user.setUserType(newUser.userType);
            user.setSignIn(true);
          }
          return Promise.resolve(isSuccess);
        });
    }

  }
}
